package com.bilgeadam.swing.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import com.bilgeadam.swing.model.DbModel;
import com.bilgeadam.swing.model.GenericModel;
import com.bilgeadam.swing.view.GenericView;
import com.bilgeadam.swing.view.LoginFrame;
import com.bilgeadam.swing.view.MainFrame;

/**
 *
 * @author Bora SAYINER
 * @since Dec 20, 2014 11:44:42 AM
 * @version 1.0
 */
public class ApplicationController {

	private GenericView loginFrame;
	private GenericModel model;

	public ApplicationController() {
		this.loginFrame = new LoginFrame();
		this.model = new DbModel();
		initalizeEvents();
	}

	private void initalizeEvents() {
		loginFrame.registerExitButton(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				int result = JOptionPane.showConfirmDialog(null, "Are you sure?", "Exit", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
				if (result == JOptionPane.YES_OPTION) {
					System.exit(0);
				}
			}
		});
		loginFrame.registerLoginButton(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String userName = loginFrame.getUserName();
				String password = loginFrame.getPassword();
				boolean result = model.validateUser(userName, password);
				if (result) {
					MainFrame mainFrame = new MainFrame(userName);
					loginFrame.setVisible(false);
					mainFrame.setVisible(true);
				} else {
					JOptionPane.showMessageDialog(null, "Username or password incorrect!", "Error", JOptionPane.ERROR_MESSAGE);
					loginFrame.clearAllTextFields();
				}
			}
		});
	}

	public void startApplication() {
		loginFrame.setVisible(true);
	}

}
